package com.xydtech.ecard.statistics.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xydtech.common.annotation.DataScope;
import com.xydtech.common.config.XydtechBusiPlatConfig;
import com.xydtech.common.constant.Constants;
import com.xydtech.common.constant.CreditConstants;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.core.domain.entity.SysUser;
import com.xydtech.common.core.text.Convert;
import com.xydtech.common.enums.ApiContant;
import com.xydtech.common.exception.ApiException;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.AESEncryptionUtils;
import com.xydtech.common.utils.DateUtils;
import com.xydtech.common.utils.PdfUtil;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.uuid.IdUtils;
import com.xydtech.data.DataPlatHttpUtils;
import com.xydtech.ecard.statistics.domain.EcardReportQuery;
import com.xydtech.ecard.statistics.mapper.EcardReportQueryMapper;
import com.xydtech.ecard.statistics.service.IEcardReportQueryService;
import com.xydtech.system.mapper.SysDeptMapper;
import com.xydtech.system.mapper.SysUserMapper;
import com.xydtech.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电子名片报告查询记录Service业务层处理
 *
 * @author xydtech
 * @date 2022-02-24
 */
@Service
public class EcardReportQueryServiceImpl implements IEcardReportQueryService {
    @Autowired
    private EcardReportQueryMapper ecardReportQueryMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    DataPlatHttpUtils dataPlatHttpUtils;

    /**
     * 查询电子名片报告查询记录
     *
     * @param id 电子名片报告查询记录主键
     * @return 电子名片报告查询记录
     */
    @Override
    public EcardReportQuery selectEcardReportQueryById(Long id, String salt) {
        EcardReportQuery reportQuery = ecardReportQueryMapper.selectEcardReportQueryById(id);
        if (reportQuery != null) {
            try {
                //数据解密（手机号、身份证号）
                if (!StringUtils.objIsNullOrEmpty(reportQuery.getTelNo())) {
                    reportQuery.setTelNo(AESEncryptionUtils.decrypt(reportQuery.getTelNo(), salt));
                }
                if (!StringUtils.objIsNullOrEmpty(reportQuery.getIdNo())) {
                    reportQuery.setTelNo(AESEncryptionUtils.decrypt(reportQuery.getIdNo(), salt));
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return reportQuery;
    }

    /**
     * 查询电子名片报告查询记录列表
     *
     * @param ecardReportQuery 电子名片报告查询记录
     * @return 电子名片报告查询记录
     */
    @Override
    @DataScope(deptAlias = "a", userAlias = "a")
    public List<EcardReportQuery> selectEcardReportQueryList(EcardReportQuery ecardReportQuery, String salt) {
        try {
            //数据加密（手机号、身份证号）
            if (!StringUtils.objIsNullOrEmpty(ecardReportQuery.getTelNo())) {
                ecardReportQuery.setTelNo(AESEncryptionUtils.encrypt(ecardReportQuery.getTelNo(), salt));
            }
            if (!StringUtils.objIsNullOrEmpty(ecardReportQuery.getIdNo())) {
                ecardReportQuery.setIdNo(AESEncryptionUtils.encrypt(ecardReportQuery.getIdNo(), salt));
            }
            List<EcardReportQuery> ecardReportQueryList = ecardReportQueryMapper.selectEcardReportQueryList(ecardReportQuery);
            if (ecardReportQueryList.size() > 0) {
                for (EcardReportQuery reportQuery : ecardReportQueryList) {
                    //数据解密（手机号、身份证号）
                    if (!StringUtils.objIsNullOrEmpty(reportQuery.getTelNo())) {
                        reportQuery.setTelNo(AESEncryptionUtils.decrypt(reportQuery.getTelNo(), salt));
                    }
                    if (!StringUtils.objIsNullOrEmpty(reportQuery.getIdNo())) {
                        reportQuery.setIdNo(AESEncryptionUtils.decrypt(reportQuery.getIdNo(), salt));
                    }
                }
            }
            return ecardReportQueryList;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 新增电子名片报告查询记录
     *
     * @param ecardReportQuery 电子名片报告查询记录
     * @return 结果
     */
    @Override
    public int insertEcardReportQuery(EcardReportQuery ecardReportQuery, String salt) throws Exception {
        //查询用户信息
        SysUser user = userMapper.selectUserById(ecardReportQuery.getUserId());
        if (user != null) {
            try {
                //数据解密（手机号、身份证号）
                if (!StringUtils.objIsNullOrEmpty(user.getPhonenumber())) {
                    user.setPhonenumber(AESEncryptionUtils.decrypt(user.getPhonenumber(), salt));
                }
                if (!StringUtils.objIsNullOrEmpty(user.getCardNum())) {
                    user.setCardNum(AESEncryptionUtils.decrypt(user.getCardNum(), salt));
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        String appId = "";
        Map<String, Object> params = new HashMap<>();
        params.put("phoneNumbers", ecardReportQuery.getTelNo());
        params.put("name", ecardReportQuery.getCname());
        params.put("idCardNumber", ecardReportQuery.getIdNo());
        JSONObject jsonUrl = createReport(appId, ecardReportQuery.getDeptId(), user.getUserName(), ecardReportQuery.getCustType(), params);
        ecardReportQuery.setReportUrl(jsonUrl.getString("viewPath"));
        try {
            //数据加密（手机号、身份证号）
            if (!StringUtils.objIsNullOrEmpty(ecardReportQuery.getTelNo())) {
                ecardReportQuery.setTelNo(AESEncryptionUtils.encrypt(ecardReportQuery.getTelNo(), salt));
            }
            if (!StringUtils.objIsNullOrEmpty(ecardReportQuery.getIdNo())) {
                ecardReportQuery.setIdNo(AESEncryptionUtils.encrypt(ecardReportQuery.getIdNo(), salt));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ecardReportQueryMapper.insertEcardReportQuery(ecardReportQuery);
    }

    /**
     * 修改电子名片报告查询记录
     *
     * @param ecardReportQuery 电子名片报告查询记录
     * @return 结果
     */
    @Override
    public int updateEcardReportQuery(EcardReportQuery ecardReportQuery, String salt) {
        try {
            //数据加密（手机号、身份证号）
            if (!StringUtils.objIsNullOrEmpty(ecardReportQuery.getTelNo())) {
                ecardReportQuery.setTelNo(AESEncryptionUtils.encrypt(ecardReportQuery.getTelNo(), salt));
            }
            if (!StringUtils.objIsNullOrEmpty(ecardReportQuery.getIdNo())) {
                ecardReportQuery.setIdNo(AESEncryptionUtils.encrypt(ecardReportQuery.getIdNo(), salt));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ecardReportQueryMapper.updateEcardReportQuery(ecardReportQuery);
    }

    /**
     * 批量删除电子名片报告查询记录
     *
     * @param ids 需要删除的电子名片报告查询记录主键
     * @return 结果
     */
    @Override
    public int deleteEcardReportQueryByIds(String ids) {
        return ecardReportQueryMapper.deleteEcardReportQueryByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除电子名片报告查询记录信息
     *
     * @param id 电子名片报告查询记录主键
     * @return 结果
     */
    @Override
    public int deleteEcardReportQueryById(Long id) {
        return ecardReportQueryMapper.deleteEcardReportQueryById(id);
    }

    /**
     * 生成报告
     *
     * @param appId
     * @param deptId
     * @param userName
     * @param prdTarget
     * @param params
     * @return java.lang.String
     * @throws
     * @Title: createReport
     * @author JHON
     * @Date 2022/2/24 9:57
     **/
    @Override
    public JSONObject createReport(String appId, Long deptId, String userName, String prdTarget, Map<String, Object> params) throws Exception {
        JSONObject jsonObject = new JSONObject();
        //查询法人机构
        SysDept dept = sysDeptMapper.selectSecondLevelDeptByDeptId(deptId);
        if (dept == null) {
            dept = new SysDept();
            dept.setDeptId(deptId);
        }
        /**
         * 生成报告:初审报告接口编号（PRD_TARGET_NATURAL_PERSON：个人的；DATAPLAT_INTERFACENUMREPORT_KEY：企业的）
         */
        String interfaceNumReport = configService.selectConfigByKey(CreditConstants.PRD_TARGET_NATURAL_PERSON.equals(prdTarget) ? ApiContant.DATAPLAT_INTERFACENUMREPORT_KEY : ApiContant.DATAPLAT_INTERFACENUMORGREPORT_KEY, dept.getDeptId());
        ResponseModel responseModel = dataPlatHttpUtils.dataPlatRequest(interfaceNumReport, appId, ApiContant.APPLETTYPE_ECARD, dept.getDeptId(), params);
        if (responseModel == null || responseModel.getCode() != 0) {
            throw new ApiException("生成初审报告失败:" + responseModel.getMsg());
        }
        /**
         * 将拿到的报告PDF转换成图片文件，并将地址存储在数据库中（为兼容前端IOS和Android无法展示PDF的问题，修改成图片）
         */
        JSONObject reportInfoObj = JSONObject.parseObject(JSON.toJSONString(responseModel.getData()));
        String reportUrl = reportInfoObj.getString("reportUrl");

        //首先是获取到PDF文件
        String fileName = IdUtils.randomUUID() + ".png";
        //存储到硬盘中的物理地址
        String filePath = XydtechBusiPlatConfig.getProfile() + "/" + dept.getDeptId() + "/ecard/report/";
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        //存储到数据库中的地址
        String viewPath = Constants.RESOURCE_PREFIX + "/" + dept.getDeptId() + "/ecard/report/" + fileName;
        //文件写入磁盘
        String pdfFile = filePath + IdUtils.randomUUID() + ".pdf";
        StringUtils.base64StringToPdf(reportInfoObj.get("reportData").toString(), pdfFile);
        // pdf转图片加水印
        String imgPath = filePath + fileName;
        PdfUtil.pdfToImgAddWaterMask(pdfFile, imgPath, userName, 2);
        //PDF文件返回路径
        String pdfUrl = Constants.RESOURCE_PREFIX + pdfFile.substring(pdfFile.indexOf(dept.getDeptId().toString()) - 1, pdfFile.length());
        jsonObject.put("newPdfFile", pdfUrl);
        jsonObject.put("viewPath", viewPath);
        return jsonObject;
    }


    /**
     * 合并图片
     *
     * @param image1
     * @param image2
     * @return
     */
    private static BufferedImage merge(BufferedImage image1, BufferedImage image2) {
        BufferedImage combined = new BufferedImage(
                image1.getWidth(),
                image1.getHeight() + image2.getHeight(),
                BufferedImage.TYPE_INT_RGB);

        Graphics g = combined.getGraphics();
        g.drawImage(image1, 0, 0, null);
        g.drawImage(image2, 0, image1.getHeight(), null);
        g.dispose();
        return combined;
    }

    /**
     * 添加水印
     *
     * @param image   图片
     * @param maskStr 水印字符串
     * @return
     */
    private static BufferedImage addWaterMask(BufferedImage image, String maskStr) {

        int imgHeight = image.getHeight();
        int imgWidth = image.getWidth();

        //获取 Graphics2D 对象
        Graphics2D g = image.createGraphics();
        //设置绘图区域
        g.drawImage(image, imgWidth, imgHeight, null);
        //设置字体
        int timeFontSize = 50;
        Font font = new Font("Microsoft YaHei", Font.PLAIN, timeFontSize);
        g.setFont(font);
        // 根据图片的背景设置水印颜色
        g.setColor(Color.GRAY);
        //设置透明
        AlphaComposite alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.35f);
        g.setComposite(alphaComposite);
        //设置抗锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //设置偏转
        g.rotate(-Math.PI / 5, imgWidth / 2, imgHeight / 2);
        for (int x = -imgHeight; x < imgHeight; x += 600) {
            for (int y = -imgHeight; y < imgHeight; y += 300) {
                g.drawString(maskStr + " " + DateUtils.getDate(), x, y);
            }
        }

        g.dispose();

        return image;
    }
}
